import { createRouter, createWebHashHistory, RouterView } from 'vue-router'
import store from '@/store'
import { h } from 'vue'

const Layout = () => import('@/views/Layout')
const Home = () => import('@/views/home')
const TopCategory = () => import('@/views/category/index')
const SubCategory = () => import('@/views/category/sub')
const Goods = () => import('@/views/goods/index')
const Login = () => import('@/views/login/index')
const Callback = () => import('@/views/login/callback')
const Cart = () => import('@/views/cart/index')
const Checkout = () => import('@/views/member/pay/checkout')
const PayIndex = () => import('@/views/member/pay/index')
const PayResult = () => import('@/views/member/pay/result')
// 个人中心
const MemberLayout = () => import('@/views/member/Layout')
const MemberHome = () => import('@/views/member/home/index')
const MemberOrder = () => import('@/views/member/order/index')
const MemberOrderDetail = () => import('@/views/member/order/detail')

const routes = [
  // 一级路由布局容器
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '/',
        component: Home
      },
      {
        path: '/category/:id',
        component: TopCategory
      },
      {
        path: '/category/sub/:id',
        component: SubCategory
      },
      {
        path: '/product/:id',
        component: Goods
      },
      {
        path: '/cart',
        component: Cart
      },
      {
        path: '/member/checkout',
        component: Checkout
      },
      {
        path: '/member/pay',
        component: PayIndex
      },
      {
        path: '/pay/callback',
        component: PayResult
      },
      {
        path: '/member',
        component: MemberLayout,
        children: [
          {
            path: '/member',
            component: MemberHome
          },
          {
            path: '/member/order',
            component: { render: () => h(<RouterView/>) },
            children: [
              {
                path: '',
                component: MemberOrder
              },
              {
                path: ':id',
                component: MemberOrderDetail
              }
            ]
          }
        ]
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/login/callback',
    component: Callback
  }
]

// 创建路由实例
const router = createRouter({
  // 使用hash方式实现路由
  history: createWebHashHistory(),
  // 配置路由规则，写法和之前一样
  routes,
  scrollBehavior () {
    // 控制每次路由跳转显示页面的位置：到顶部
    return {
      // vue2.0使用x，y
      // vue3.0使用left和top
      left: 0,
      top: 0
    }
  }
})

// 前置导航守卫
router.beforeEach((to, from, next) => {
  // 需要登录的路由：地址前以/member开头
  // 用户的状态
  const { token } = store.state.user.profile
  // 不带redirectUrl写问题：登录成功后无法跳转回来
  // encodeURIComponent将有字符串的url转为编码
  if (!token && to.path.startsWith('/member')) return next('/login?redirectUrl=' + encodeURIComponent(to.path))
  next()
})

export default router
